package br.elsa.survey.tests.utils;

import java.util.LinkedList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import br.elsa.survey.domain.questions.CheckboxQuestion;
import br.elsa.survey.domain.questions.DiscursiveQuestion;
import br.elsa.survey.domain.questions.Question;
import br.elsa.survey.domain.questions.RadioQuestion;
import br.elsa.survey.domain.survey.Survey;

/**
 * Utility Class for Tests
 * 
 * @author diego
 * @since 2010-10-27
 */
public class DatabaseUtils {

	public static EntityManager getLocalEntityManager() {

		// Configures a local persistence context to use in tests context
		EntityManagerFactory emf = Persistence.createEntityManagerFactory("elsa-survey-jpa-integration-tests");
		EntityManager entityManager = (EntityManager) emf.createEntityManager();
		emf.close();

		return entityManager;
	}

	/**
	 * Creates and inserts one of each {@link Question} type into database
	 * 
	 * @return the number of questions inserted
	 */
	public static List<Question> insertOneQuestionOfEachQuestionType(EntityManager entityManager) {

		CheckboxQuestion checkboxQuestion = QuestionsFactory.createCheckboxQuestion(2);
		RadioQuestion radioQuestion = QuestionsFactory.createRadioQuestion(5);
		DiscursiveQuestion discursiveQuestion = QuestionsFactory.createDiscursiveQuestion();

		entityManager.getTransaction().begin();
		entityManager.persist(checkboxQuestion);
		entityManager.persist(radioQuestion);
		entityManager.persist(discursiveQuestion);
		entityManager.getTransaction().commit();

		List<Question> insertedQuestions = new LinkedList<Question>();
		insertedQuestions.add(discursiveQuestion);
		insertedQuestions.add(radioQuestion);
		insertedQuestions.add(checkboxQuestion);

		return insertedQuestions;
	}

	public static Survey insertSurveyWithOneOfEachQuestionType(EntityManager entityManager) {

		List<Question> questions = insertOneQuestionOfEachQuestionType(entityManager);
		Survey survey = SurveyFactory.createDummySurvey(questions);

		entityManager.getTransaction().begin();
		entityManager.persist(survey);
		entityManager.getTransaction().commit();

		return survey;
	}

	public static List<Survey> insertSurveysWithOneOfEachQuestionType(EntityManager entityManager, int surveysCount) {

		List<Survey> insertedSurveys = new LinkedList<Survey>();

		for (int i = 0; i < surveysCount; i++) {
			Survey survey = insertSurveyWithOneOfEachQuestionType(entityManager);
			insertedSurveys.add(survey);
		}

		return insertedSurveys;
	}
}
